package CheckersApplet;

import java.awt.*;
import java.util.ArrayList;

public class TestApplet extends java.applet.Applet {
	// TextField inputText;
	TextArea textBox;
	Button b;
	int i = 0;
	ArrayList<Move> moves;
	
	CheckersPanel checkersRed;
	CheckersPanel checkersBlack;

	public void init() {
		setLayout(null);
		// inputText = new TextField("", 15);
		b = new Button("Play");
		// add(inputText);
		textBox = new TextArea(5, 40);
		
		checkersRed = new CheckersPanel();		
		checkersBlack = new CheckersPanel();
		
		checkersRed.setColor("red");
		//checkersRed.newGame();
		checkersBlack.setToughness(4);
		
		add(checkersBlack);
		add(checkersRed);
		
		add(textBox);
		add(b);
		
		InitialPositionSet();
	}

	public void InitialPositionSet() {
		resize(1200, 450);
		checkersRed.reshape(20, 10, 400, 400);
		checkersBlack.reshape(500, 10, 400, 400);
		textBox.reshape(910, 10, 200, 400);
		b.reshape(1135, 205, 50, 30);
		
	}
	public void append(String msg) {
		textBox.append(msg);
		textBox.append("\n");
	}

	public int revertMove(int pos) {
		return 34 - pos;
	}

	// JDK 1.02 style evant handling
	public boolean action(Event ev, Object arg) {

		if (ev.target instanceof Button) {

//			checkersBlack checkers1 = (checkersBlack) getAppletContext().getApplet(
//					"applet1");
//			Checkers checkersBlack = (Checkers) getAppletContext().getApplet(
//					"applet2");

			if (i == 0) {//red
				moves = ((CheckersPanel) checkersRed).newGame();
				printMovesRed(moves);
			}

			if (i > 0 && i % 2 == 1) {//black
				
				for (Move move : moves)
					moves = ((CheckersPanel) checkersBlack).makeMove(
							revertMove(move.from), revertMove(move.to));
				printMovesBlack(moves);
			}

			if (i > 0 && i % 2 == 0) {//Red
				for (Move move : moves)
					moves = ((CheckersPanel) checkersRed).makeMove(
							revertMove(move.from), revertMove(move.to));

				printMovesRed(moves);
			}
			repaint();
			i++;
		}

		return true;
	}
	
	private void printMovesRed(ArrayList<Move> moves) {
		append("-----------------------");
		append("Black:");
		if (moves == null || moves.isEmpty())
			append("Error! Empty move message received!!!!");
		for (Move move : moves) {
			append("From : " + Integer.toString(move.from) + " To: "
					+ Integer.toString(move.to));
		}
		append("-----------------------");
	}

	private void printMovesBlack(ArrayList<Move> moves) {
		append("-----------------------");
		append("Red:");
		if (moves == null || moves.isEmpty())
			append("Error! Empty move message received!!!!");
		for (Move move : moves) {
			append("From : " + Integer.toString(revertMove(move.from))
					+ " To: " + Integer.toString(revertMove(move.to)));
		}
		append("-----------------------");
	}
}